/*
 * Copyright 2011 jmarsden.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cc.plural.jsonij.jpath.functions;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cc.plural.jsonij.Value;
import cc.plural.jsonij.jpath.JPathRuntimeException;
import cc.plural.jsonij.jpath.functions.FunctionArgument.ARGUMENT_TYPE;
import cc.plural.jsonij.jpath.functions.FunctionArgument.AttributeArgument;
import cc.plural.jsonij.jpath.functions.FunctionArgument.ValueArgument;

/**
 *
 * @author jmarsden
 */
public class RegexFunction extends Function {

    public RegexFunction() {
        this.functionName = "regex";
        this.argumentTypeList = new ArrayList<Class<? extends FunctionArgument>>();
        this.argumentTypeList.add(AttributeArgument.class);
        this.argumentTypeList.add(ValueArgument.class);
    }

    @Override
    public Value evaluate(FunctionArgument[] args, Value value) {
        if(Array.getLength(args) != 2) {
            throw new JPathRuntimeException("InvalidArgCount");
        }
        
        if(args[0] == null || args[0].type != ARGUMENT_TYPE.ATTRIBUTE) {
            throw new JPathRuntimeException("InvalidArg", args[0]);
        }
        
        if(args[1] == null || args[1].type != ARGUMENT_TYPE.VALUE) {
            throw new JPathRuntimeException("InvalidArg", args[1]);
        }
        
        String attributeName = ((AttributeArgument) args[0]).getAttributeName();
        
        if(!value.has(attributeName)) {
            return null;
        }
        
        Value regexValue = ((ValueArgument) args[1]).getValue();
        
        if(regexValue.getValueType() != Value.TYPE.STRING) {
            throw new JPathRuntimeException("InvalidArg", args[1]);
        }
        
        Value matchValue = value.get(attributeName);
        
        Pattern pattern = Pattern.compile(regexValue.getString());
        Matcher matcher = pattern.matcher(matchValue.getString());
        
        if(matcher.matches()) {
            return matchValue;
        } else {
            return null;
        }
    }
    
}
